<?php
namespace frontend\controllers;

use common\models\Wxuser;
use frontend\models\User;
use Yii;
use yii\base\Exception;
use yii\web\Controller;
use yii\filters\VerbFilter;

/**
 * Class WxwebController
 * @package frontend\controllers
 */
class WxwebController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['post'],
                ],
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
            ],
        ];
    }

    /**
     * http://localhost/wx/frontend/web/index.php?r=wxweb/createmenu
     * 创建菜单
     * Displays homepage.
     *  $this->createMenu([
     *      [
     *           'type' => 'view',
     *           'name' => '最新资讯',
     *           'url' => 'https://mp.weixin.qq.com/s?__biz=MzAxMTQ4NjIyNg==&tempkey=OTM3X01hVythR1pDY05zbnZ1V1p3R1dZd3BNTWpEdDh2S0FCdmJ2SWh3ZjFVY1VkbDJ1MHdOY3VBczlpV1Q4bWU3RjU4VXA0UW13Rlp6U2hTNnIyUlgzMmJWTUkyajE0N3NhZURDZ0tOaFloSXRqQi05MDlTM2NzaVZDdzNnUVNZcU9wX0ZlNDc3ajVUT2tzS29YU0w2bzFIN2UtcENSU2pfSVpHN0c1cHd%2Bfg%3D%3D&chksm=035b22ab342cabbdb6992830cf31c62924d13f14b84d777d033fdb36c9c4885547fd57d46e84#rd'
     *      ],
     * {

    "type":"click",

    "name":"今日歌曲",

    "key":"V1001_NEWS"

    },
     *      [
     *           'type' => 'view',
     *           'name' => '在线商城',
     *           'url' => 'http://shop.m.jd.com/?shopId=590399'
     *      ]
     *      [
     *           'type' => 'view',
     *           'name' => 'APP下载',
     *           'url' => 'http://www.pooai.com/mobile/appDown.html'
     *      ]
     *      ...
     * ]);
     * "sub_button":[
    {
    "type":"view",
    "name":"搜索",
    "url":"http://www.soso.com/"},
    {
    "type":"miniprogram",
    "name":"wxa",
    "url":"http://mp.weixin.qq.com",
    "appid":"wx286b93c14bbf93aa",
    "pagepath":"pages/lunar/index"
    },
     * @return mixed
     */
    public function actionCreatemenu()
    {
        /** @var \callmez\wechat\sdk\Wechat $wechat $wechat */
        $wechat = Yii::$app->wechat;
//        $url = 'http://120.76.213.82/wx/frontend/web/index.php?r=wxweb/bind';
//        $bandingUrl = $wechat->getOauth2AuthorizeUrl($url,'authorize','snsapi_userinfo');
        $wxshopUrl = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx40f4453940be5dee&redirect_uri='.Yii::$app->params['domurl'].'wx%2Ffrontend%2Fweb%2Findex.php%3Fr%3Dsite%252Fsite%252Fsignup&response_type=code&scope=snsapi_userinfo&state=authorize#wechat_redirect';
        $param = [
                    [
                        'type' => 'click',
                        'name' => '最新资讯',
                        'key' => 'V1001_NEWS'
                    ],
                    [
                            'type' => 'view',
                            'name' => '在线商城',
//                            "sub_button"=>
//                                [
//                                    ['type' => 'view',
//                                        'name' => '京东商城',
//                                        'url' => 'http://shop.m.jd.com/?shopId=590399'],
//                                    ['type' => 'view',
//                                        'name' => '小普返利商城',
//                                        'url' => 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx5dee5a1c01f37b68&redirect_uri=http%3A%2F%2Fwww.pooai.cn%2Fwx%2Ffrontend%2Fweb%2Findex.php%3Fr%3Dsite%252Fsite%252Findex&time=1100&response_type=code&scope=snsapi_userinfo&state=authorize#wechat_redirect'],
//                                ]
                            'url' => 'http://shop.m.jd.com/?shopId=590399'
                      ],
                        [
                            "name"=>"客户服务",
                            "sub_button"=>
                            [
                               ['type' => 'view',
                                   'name' => 'APP下载',
                                   'url' => 'http://www.pooai.com/mobile/appDown.html'],
                                ['type' => 'view',
                                    'name' => '安装视频',
                                    'url' => 'https://v.qq.com/x/page/w0367zzf2m0.html?winzoom=1'],
                                ['type' => 'view',
                                    'name' => '常见问题',
                                    'url' => 'http://www.pooai.cn/wx/frontend/web/wxPage/xiaopu.html'],
                            ]
                        ]

        ];
        $wechat->createMenu($param);
        return 0;
    }

    /**
     * 获取微信用户信息
     */
    public function actionBind()
    {
        $code = isset($_GET['code'])?$_GET['code']:'';
        if($code) {
            /** @var \callmez\wechat\sdk\Wechat $wechat $wechat */
            $wechat = Yii::$app->wechat;
            try{
                $wxInfo = $wechat->getOauth2AccessToken($code);
                $openid = $wxInfo['openid'];
                $menberInfo = $wechat->getMemberInfo($openid);

                $user = Wxuser::findOne(['openid'=>$openid]);
                if($user){
                    return '绑定成功';
                }
                $user = new Wxuser();
                $user->openid = $openid;
                $user->unionid = $wxInfo['unionid'];
                $user->wx_name = $menberInfo['nickname'];
                $user->wx_images = $menberInfo['headimgurl'];
                $user->wx_name = $menberInfo['nickname'];
                $user->username = $menberInfo['nickname'];
                $user->sex = $menberInfo['sex'];
                if($user->save()){
                    Yii::$app->session->set('openid',$openid);
                    Yii::$app->session->set('unionid',$openid);
                    Yii::$app->session->set('wx_name',$menberInfo['nickname']);
                    Yii::$app->session->set('wx_images', $menberInfo['headimgurl']);
                    Yii::$app->session->set('wx_name',$menberInfo['nickname']);
                    print_r($user);exit;
                }
                print_r($user->errors);exit;
            }catch (Exception $e){
                return $e->getMessage();
            }
        }
    }

    public function actionTest()
    {
        /** @var \callmez\wechat\sdk\Wechat $wechat $wechat */
        $wechat = Yii::$app->wechat;
        $url = $wechat->getOauth2AuthorizeUrl(\Yii::$app->params['domurl'].'wx/frontend/web/index.php?r=wxweb/usertest','authorize','snsapi_userinfo');
        print_r($url);exit;
    }


    /**
     * 获取微信用户信息
     */
    public function actionUsertest()
    {
        /** @var \callmez\wechat\sdk\Wechat $wechat $wechat */
        $wechat = Yii::$app->wechat;
        $code = isset($_GET['code'])?$_GET['code']:'';

            $wxInfo = $wechat->getOauth2AccessToken($code);
            $openid = $wxInfo['openid'];
//            $menberInfo = $wechat->getMemberInfo($openid);
        $menberInfo = $wechat->getSnsMemberInfo($openid,$wxInfo['access_token']);
        print_r($menberInfo);
        exit;
        if($code) {
            /** @var \callmez\wechat\sdk\Wechat $wechat $wechat */
            $wechat = Yii::$app->wechat;
            try{
                $wxInfo = $wechat->getOauth2AccessToken($code);
                $openid = $wxInfo['openid'];
                $menberInfo = $wechat->getMemberInfo($openid);

                $user = Wxuser::findOne(['openid'=>$openid]);
                if($user){
                    return '绑定成功';
                }
                $user = new Wxuser();
                $user->openid = $openid;
                $user->unionid = $wxInfo['unionid'];
                $user->wx_name = $menberInfo['nickname'];
                $user->wx_images = $menberInfo['headimgurl'];
                $user->wx_name = $menberInfo['nickname'];
                $user->username = $menberInfo['nickname'];
                $user->sex = $menberInfo['sex'];
                if($user->save()){
                    Yii::$app->session->set('openid',$openid);
                    Yii::$app->session->set('unionid',$openid);
                    Yii::$app->session->set('wx_name',$menberInfo['nickname']);
                    Yii::$app->session->set('wx_images', $menberInfo['headimgurl']);
                    Yii::$app->session->set('wx_name',$menberInfo['nickname']);
                    print_r($user);exit;
                }
                print_r($user->errors);exit;
            }catch (Exception $e){
                return $e->getMessage();
            }
        }
    }
}
